#!/usr/bin/python3

import subprocess
import IPy
import ipaddress

def ip_test(ip):
    # 使用IPy包转换为IP格式
    ip = IPy.IP(ip)
    # 创建使用IP文件和未使用IP文件
    file1 = open("used_ips.txt",'w+')
    file2 = open("unused_ips.txt",'w+')
    # 遍历并pingIP
    for i in ip:
        # 使用subprocess包执行ping命令
        test = subprocess.Popen(f'ping {i} -c 1 -w 1',shell=True)
        # 查看是否ping成功
        k = test.wait()
        # k = 0表示ping成功，并将成功的IP写入used_ips.txt
        if k == 0:
            print(f"{i} is used.")
            file1.write(str(i)+'\n')
        # 否则表示未ping成功，并将未成功的IP写入unused_ips.txt
        else:
            print(f"{i} is not used.")
            file2.write(str(i)+'\n')

ips = input("Please input the ip you want to test:")
try:
    # 调用ipaddress包判断输入的是否合法
    ipaddress.ip_network(ips,strict=False)
    # 不合法就提示
except ValueError as ve:
    print("sorry!Your input is incorrect,pls try again!")
    # 合法就调用ip_test()函数
else:
    ip_test(ips)

